"use client";
import React, { useState, useEffect } from 'react';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Badge } from '@/components/ui/badge';
import { Loader2, Database, Settings, FileText, MapPin } from 'lucide-react';

interface Device {
  id: number;
  device_id: string;
  name: string;
  specialty: string;
  classification_name: string;
  classification_code: string;
}

interface Parameter {
  id: number;
  parameter_name: string;
  parameter_value: string;
  data_type: string;
  is_required: boolean;
  measurement_unit?: string;
}

interface DeviceWithParameters {
  device: Device;
  namingParameters: Parameter[];
  positionParameters: Parameter[];
  baseParameters: Parameter[];
}

export default function SqliteDemoPage() {
  const [devices, setDevices] = useState<Device[]>([]);
  const [selectedDevice, setSelectedDevice] = useState<DeviceWithParameters | null>(null);
  const [specialties, setSpecialties] = useState<string[]>([]);
  const [selectedSpecialty, setSelectedSpecialty] = useState<string>('');
  const [loading, setLoading] = useState(false);
  const [stats, setStats] = useState<any>(null);

  useEffect(() => {
    fetchDevices();
    fetchStats();
  }, []);

  useEffect(() => {
    if (selectedSpecialty && selectedSpecialty !== 'all') {
      fetchDevicesBySpecialty(selectedSpecialty);
    } else {
      fetchDevices();
    }
  }, [selectedSpecialty]);

  const fetchDevices = async () => {
    try {
      const response = await fetch('/api/sqlite-devices');
      const data: Device[] = await response.json();
      setDevices(data);
      
      const uniqueSpecialties = [...new Set(data.map((d: Device) => d.specialty))];
      setSpecialties(uniqueSpecialties);
    } catch (error) {
      console.error('获取设备列表失败:', error);
    }
  };

  const fetchDevicesBySpecialty = async (specialty: string) => {
    try {
      const response = await fetch(`/api/sqlite-devices?specialty=${encodeURIComponent(specialty)}`);
      const data = await response.json();
      setDevices(data);
    } catch (error) {
      console.error('获取专业设备失败:', error);
    }
  };

  const fetchStats = async () => {
    try {
      const response = await fetch('/api/sqlite-dashboard-stats');
      const data = await response.json();
      setStats(data);
    } catch (error) {
      console.error('获取统计信息失败:', error);
    }
  };

  const fetchDeviceDetails = async (deviceId: string) => {
    setLoading(true);
    try {
      const response = await fetch(`/api/sqlite-devices?deviceId=${deviceId}&withParameters=true`);
      const data = await response.json();
      setSelectedDevice(data);
    } catch (error) {
      console.error('获取设备详情失败:', error);
    } finally {
      setLoading(false);
    }
  };

  const renderParameterTable = (title: string, parameters: Parameter[], icon: React.ReactNode) => (
    <Card>
      <CardHeader>
        <CardTitle className="flex items-center space-x-2 text-lg">
          {icon}
          <span>{title}</span>
          <Badge variant="secondary">{parameters.length}</Badge>
        </CardTitle>
      </CardHeader>
      <CardContent>
        {parameters.length > 0 ? (
          <div className="space-y-2">
            {parameters.map((param) => (
              <div key={param.id} className="flex justify-between items-center p-2 border rounded">
                <div className="flex items-center space-x-2">
                  <span className="font-medium">{param.parameter_name}</span>
                  {param.is_required && <Badge variant="destructive" className="text-xs">必填</Badge>}
                </div>
                <div className="text-right">
                  <div className="text-sm text-gray-600">
                    {param.parameter_value || '(未填写)'}
                  </div>
                  {param.measurement_unit && (
                    <div className="text-xs text-gray-500">单位: {param.measurement_unit}</div>
                  )}
                </div>
              </div>
            ))}
          </div>
        ) : (
          <p className="text-gray-500 text-center py-4">暂无参数数据</p>
        )}
      </CardContent>
    </Card>
  );

  return (
    <div className="p-6 space-y-6">
      <div className="flex justify-between items-center">
        <h1 className="text-3xl font-bold">SQLite 数据库演示</h1>
        <Button onClick={fetchStats} variant="outline">
          <Database className="w-4 h-4 mr-2" />
          刷新统计
        </Button>
      </div>

      {stats && (
        <Card>
          <CardHeader>
            <CardTitle>数据库统计</CardTitle>
            <CardDescription>当前SQLite数据库中的设备统计信息</CardDescription>
          </CardHeader>
          <CardContent>
            <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
              <div className="text-center p-4 bg-blue-50 rounded-lg">
                <div className="text-2xl font-bold text-blue-600">{stats.totalDevices}</div>
                <div className="text-sm text-gray-600">总设备数</div>
              </div>
              {stats.specialtyStats?.slice(0, 3).map((stat: any, index: number) => (
                <div key={index} className="text-center p-4 bg-gray-50 rounded-lg">
                  <div className="text-xl font-bold">{stat.count}</div>
                  <div className="text-sm text-gray-600">{stat.name}</div>
                </div>
              ))}
            </div>
          </CardContent>
        </Card>
      )}

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        <Card>
          <CardHeader>
            <CardTitle>设备列表</CardTitle>
            <CardDescription>SQLite数据库中的所有设备</CardDescription>
            <div className="pt-2">
              <Select value={selectedSpecialty} onValueChange={setSelectedSpecialty}>
                <SelectTrigger>
                  <SelectValue placeholder="选择专业筛选" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">全部专业</SelectItem>
                  {specialties.map((specialty) => (
                    <SelectItem key={specialty} value={specialty}>
                      {specialty}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
          </CardHeader>
          <CardContent>
            <div className="space-y-2 max-h-96 overflow-y-auto">
              {devices.map((device) => (
                <div
                  key={device.id}
                  className="p-3 border rounded-lg cursor-pointer hover:bg-gray-50 transition-colors"
                  onClick={() => fetchDeviceDetails(device.device_id)}
                >
                  <div className="flex justify-between items-start">
                    <div>
                      <div className="font-medium">{device.name}</div>
                      <div className="text-sm text-gray-600">{device.device_id}</div>
                      <div className="text-xs text-gray-500">{device.classification_name}</div>
                    </div>
                    <Badge variant="outline">{device.specialty}</Badge>
                  </div>
                </div>
              ))}
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardHeader>
            <CardTitle>设备详情</CardTitle>
            <CardDescription>选择左侧设备查看详细信息和参数</CardDescription>
          </CardHeader>
          <CardContent>
            {loading ? (
              <div className="flex items-center justify-center py-8">
                <Loader2 className="w-6 h-6 animate-spin mr-2" />
                加载中...
              </div>
            ) : selectedDevice ? (
              <div className="space-y-4">
                <div className="p-4 border rounded-lg">
                  <h3 className="font-semibold text-lg">{selectedDevice.device.name}</h3>
                  <p className="text-sm text-gray-600">设备编号: {selectedDevice.device.device_id}</p>
                  <p className="text-sm text-gray-600">分类: {selectedDevice.device.classification_name}</p>
                  <p className="text-sm text-gray-600">专业: {selectedDevice.device.specialty}</p>
                </div>
                
                <div className="grid grid-cols-1 gap-4">
                  {renderParameterTable(
                    '命名参数',
                    selectedDevice.namingParameters,
                    <FileText className="w-4 h-4" />
                  )}
                  {renderParameterTable(
                    '位置参数',
                    selectedDevice.positionParameters,
                    <MapPin className="w-4 h-4" />
                  )}
                  {renderParameterTable(
                    '基础参数',
                    selectedDevice.baseParameters,
                    <Settings className="w-4 h-4" />
                  )}
                </div>
              </div>
            ) : (
              <div className="text-center py-8 text-gray-500">
                请选择一个设备查看详情
              </div>
            )}
          </CardContent>
        </Card>
      </div>
    </div>
  );
}
 